const {
	ershoufangBaseUrl, xinfangBaseUrl, ershoufangchengjiaoBaseUrl
} = require('./beike');

const cityCodeMap = require('../json/city.json');
const areaCodeMap = require('../json/area.json');
const HOUSE_TYPE = require('../constant/index');

class TaskPublisher {
	constructor() {
		this.name = 'task-publisher'
	}

	/**
	 * 生成目标url请求地址
	 * 二手房地址、新房地址
	 * @param {*} type
	 * @param {*} city
	 * @param {*} area
	 * @returns
	 */
	generateBaseUrl(type, city, area) {
		let url = '';
		const cityCode = cityCodeMap[city];

		// 二手房
		if (type === HOUSE_TYPE.ER_SHOU_FANG) {
			url = ershoufangBaseUrl;
		}

		// 新房
		if (type === HOUSE_TYPE.XIN_FANG) {
			url = xinfangBaseUrl;
		}

		// 二手房成交
		if (type === HOUSE_TYPE.ER_SHOU_FANG_CHENG_JIAO) {
			url = ershoufangchengjiaoBaseUrl;
		}

		// 区域
		if (area) {
			const areaCode = areaCodeMap[city]
				.filter(item => {
					const result = Object.entries(item)[0];
					const [key, value] = result;

					return key === area;
				})
				.map(item => {
					return Object.values(item);
				})[0];

			const result = url.replace(/\/{cityCode}/, cityCode).replace(/{areaCode}/, areaCode);

			return result;
		}

		const result = url.replace(/\/{cityCode}/, cityCode).replace(/\/{areaCode}/, '');

		return result;
	}

	/**
	 * 创建爬虫任务
	 * @param {*} type 找房类型（二手房、新房）
	 * @param {*} options
	 * @returns
	 */
	create(type, options = {}) {
		const { city = '天津', area = '', page = 10 } = options;
		const base = this.generateBaseUrl(type, city, area);

		const urls = new Array(page).fill('').map((item, index) => {
			if (index === 0) {
				return base;
			}

			return base + `/pg${index + 1}/`;
		});

		return urls;
	}
}

module.exports = TaskPublisher;